//-----------------------------------------------
//              MCP3553.c
//      Arthur Benemann 21/03/2012
//-----------------------------------------------
#include "MCP3553.h"
#include "picDev.h"
#define positiveOverloadBit 0x00400000
#define negativeOverloadBit 0x00800000
#define mostNegativeValue   0xFF1FFFFF
#define mostPositiveValue   0x00200000
#define negativeValueOffset 0xFFC00000
#define minNegativeValue    0x001FFFFF
void processMCP3553Value(long *value);
long readSerialData();

void initMCP3553(void) {
    MCP3553_SCK = Ro_SCK2OUT;
    Ri_SDI2 = MCP3553_SDO;
    MCP3553_CS_tris = 0;

    initSPI1();
}

int readMCP3553(long *value) {
    int n;

    MCP3553_CS = 0;
    for (n = 0; n < 32; n++);

    if (MCP3553_SDO_pin == 0) {
        *value = readSerialData();
        processMCP3553Value(value);
        MCP3553_CS = 1;
        return READ_COMPLETED;
    } else {
        MCP3553_CS = 1;
        return NOT_FINISHED;
    }
}

void processMCP3553Value(long *value) {
    if (*value & negativeOverloadBit) {
        *value = mostNegativeValue;
    } else if (*value & positiveOverloadBit) {
        *value = mostPositiveValue;
    } else if (*value > minNegativeValue) {
        *value |= negativeValueOffset;
    }
}

long readSerialData() {
    long data;
    data = ((long) (writeSPI(0xFF))) << 16;
    data |= ((long) (writeSPI(0xFF))) << 8;
    data |= ((long) (writeSPI(0xFF)));
    return data;
}
